const Koa = require("koa");
const KoaRouter = require("koa-router");
const bodyParser = require("koa-bodyparser");
const koaCors = require("koa2-cors");
const axios = require("axios");

const app = new Koa();

const router = new KoaRouter();

app.use(bodyParser());
app.use(koaCors({ maxAge: 3600 }));
app.use(router.routes());
app.use(router.allowedMethods());

router.get("/user-info", async (ctx) => {
  const { authorization: token = "" } = ctx.request.headers;
  try {
    const {
      data: { code, data },
    } = await axios.get("http://localhost:3000/user-info", {
      headers: { authorization: token },
    });
    if (code === 0) {
      ctx.body = {
        code: 0,
        message: "用户在登录态",
        data: { username: data.username },
      };
    } else if (code === 1001) {
      ctx.body = {
        code: 1001,
        message: "用户未登录",
        data: null,
      };
    }
  } catch (e) {
    console.log(e);
  }
});

router.get("/logout", async (ctx) => {
  const { authorization: token = "" } = ctx.request.headers;
  try {
    const {
      data: { code },
    } = await axios.get("http://localhost:3000/logout", {
      headers: { authorization: token },
    });
    if (code === 0) {
      ctx.body = {
        code: 0,
        message: "用户已登出",
      };
    } else {
      ctx.body = {
        code: 1005,
        message: "用户登出失败",
      };
    }
  } catch (e) {
    console.log(e);
  }
});

app.listen(3001, () => {
  console.log("淘宝服务器运行在3001端口");
});
